﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;

namespace BuildForm
{
    public partial class Shippers : Form
    {
        SqlConnection con;
        SqlCommand cmd;
        SqlParameter param;
        SqlDataAdapter da;
        DataSet ds;
        DataView dv;
        DataTable dt;
        public Shippers()
        {
            InitializeComponent();
            initialconect();
            initialADOObject();
            LoadCustomerDisconect();
            initialform();
            cbSearchBy.SelectedIndex = 0;
        }
        #region Initial
        void initialconect()
        {
            con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        }
        void initialADOObject()
        {
            cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT * FROM Sales.Shippers";
            da = new SqlDataAdapter(cmd);
            ds = new DataSet();
            da.FillSchema(ds, SchemaType.Mapped);
            da.Fill(ds, "Sales.Shippers");
        }
        void initialform()
        {
            errorProvider1.Clear();
            btnAdd.Enabled = true;
            txtShiperID.Enabled = false;
            txtShiperID.Clear();
            txtCompanyName.Clear();
            txtSearchName.Clear();
            mtbPhone.Clear();
            btnUpdate.Enabled = false;
            btnDelete.Enabled = false;

        }  
        #endregion
        void LoadCustomerDisconect()
        {
            dt = new DataTable("Sales.Shippers");
            dt = ds.Tables["Sales.Shippers"];
            dv = new DataView(dt);
            gvShiper.DataSource = dt;
        }
        void AddShipper()
        {
            try
            {
                con.Open();
                cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "sp_Shippers_Insert";
                param = new SqlParameter("@companyname", SqlDbType.NVarChar);
                param.Size = 40;
                param.Value = txtCompanyName.Text;
                cmd.Parameters.Add(param);
                param = new SqlParameter("@phone", SqlDbType.NVarChar);
                param.Size = 24;
                param.Value = mtbPhone.Text;
                cmd.Parameters.Add(param);
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                con.Close();
                initialADOObject();
                LoadCustomerDisconect();
                btnReload.Enabled = false;
            }
        }
        void DeleteShipper()
        {
            try
            {
                con.Open();
                cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "sp_Shippers_Delete";
                param = new SqlParameter("@shipperid", SqlDbType.Int);
                param.Value = txtShiperID.Text;
                cmd.Parameters.Add(param);
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                con.Close();
                initialADOObject();
                LoadCustomerDisconect();
                btnReload.Enabled = false;
            }
        }
        void UpdateShipper()
        {
            try
            {
                con.Open();
                cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "sp_Shippers_Update";
                param = new SqlParameter("@shipperid", SqlDbType.Int);
                param.Value = txtShiperID.Text;
                cmd.Parameters.Add(param);

                param = new SqlParameter("@companyname", SqlDbType.NVarChar);
                param.Size = 40;
                param.Value = txtCompanyName.Text;
                cmd.Parameters.Add(param);

                param = new SqlParameter("@phone", SqlDbType.NVarChar);
                param.Size = 24;
                param.Value = mtbPhone.Text;
                cmd.Parameters.Add(param);

               

                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                con.Close();
                initialADOObject();
                LoadCustomerDisconect();
                btnReload.Enabled = false;
            }
        }
        bool validateinput()
        {
            try
            {
                Boolean error = false;
                string companyname = txtCompanyName.Text;
                if (companyname == "")
                {
                    errorProvider1.SetError(txtCompanyName, "Please enter Company Name");
                    error = true;
                }
                if (mtbPhone.Text.Trim() == "(   )    -")
                {
                    errorProvider1.SetError(mtbPhone, "Enter Phone Number");
                    error = true;
                }
                else
                if (!mtbPhone.MaskCompleted)
                {
                    errorProvider1.SetError(mtbPhone, "Wrong Input");
                    error = true;
                }
                
                if (error) return false;
                else return true;
            }
            catch
            {
                return false;
            }

        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            gvShiper.ClearSelection();
            initialform();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            Boolean check = true;
            if (validateinput())
            {
                try
                {
                    AddShipper();
                }
                catch
                {
                    check = false;
                    MessageBox.Show("Have an error in conection to database. \nSo we can't add this tuple ! ", "Error");
                }
                finally
                {
                    initialform();
                }
            }
            else return;
            if (check) MessageBox.Show("Add Succsess!", "Notification");
           

        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (gvShiper.SelectedRows.Count > 0)
            {
                Boolean check = true;
                try
                {
                    DialogResult rs = MessageBox.Show("Are You Sure !", "Waring", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (rs == DialogResult.Yes)
                        DeleteShipper();
                    else return;
                }
                catch
                {
                    check = false;
                    MessageBox.Show("Sorry ! Cannot Delete This Rows", "Waring !");
                }
                finally
                {
                    gvShiper.ClearSelection();
                    initialform();
                }
                if (check)
                {
                    MessageBox.Show("Susscess!", "Notification");
                    
                }
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            Boolean check = true;
            if (validateinput())
            {
                try
                {
                    DialogResult rs = MessageBox.Show("Are You Sure !", "Waring", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (rs == DialogResult.Yes)
                        UpdateShipper();
                    else return;
                }
                catch
                {
                    check = false;
                    MessageBox.Show("Have an information are using by orther table! ", "Error");
                }
                finally
                {
                    gvShiper.ClearSelection();
                    initialform();
                }
            }
            else return;
            if (check)
            {
                MessageBox.Show("Update Succsess!", "Notification");
            }

        }

        private void btnReload_Click(object sender, EventArgs e)
        {
            try
            {
                initialADOObject();
                LoadCustomerDisconect();
                btnReload.Enabled = false;
            }
            catch
            {
                MessageBox.Show("Connect Fail !", "Error");
            }
        }
        private void txtSearchName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnSearch_Click(sender, e); ;
            }
        }
        private void btnSearch_Click(object sender, EventArgs e)
        {
            int tmp = cbSearchBy.SelectedIndex;
            if (tmp == 0)
            {
                MessageBox.Show("Please Choise Search by ?", "Notification");
                return;
            }
            if (tmp == 1)
                SearchShipper();
            if (tmp == 2)
                Searchphone();
            if (txtSearchName.Text.Trim() != "")
                btnReload.Enabled = true;
        }

        private void gvShiper_SelectionChanged(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            if (gvShiper.SelectedRows.Count > 0)
            {
                try
                {
                    btnAdd.Enabled = false;
                    btnDelete.Enabled = true;
                    btnUpdate.Enabled = true;
                    DataGridViewRow r = gvShiper.SelectedRows[0];
                    txtShiperID.Text = r.Cells[0].Value.ToString();
                    txtCompanyName.Text = r.Cells[1].Value.ToString();
                    mtbPhone.Text = r.Cells[2].Value.ToString();
                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.Message);
                }
            }
        }
        void SearchShipper()
        {
            try
            {
                dv = new DataView(dt);
                dv.RowFilter = string.Format("companyname LIKE'%{0}%'", txtSearchName.Text);
                gvShiper.DataSource = dv;
            }
            catch
            {
                MessageBox.Show("Search Fail !", "Error");
            }
        }
        void Searchphone()
        {
            try
            {
                dv = new DataView(dt);
                dv.RowFilter = string.Format("phone LIKE '%{0}%'", txtSearchName.Text);
                gvShiper.DataSource = dv;
            }
            catch
            {
                MessageBox.Show("Search Fail !", "Error");
            }
        }
    }
}
